package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.TcUser;
import com.zhentao.pojo.WxUser;
import com.zhentao.service.WxService;
import com.zhentao.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/wxUser")
public class WxUserController {


    @Autowired
    private WxUserService UserService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> params) {
        String code = params.get("code");
        String nickname = params.get("nickname");
        String avatarUrl = params.get("avatarUrl");
        System.out.println("code=" + code);
        System.out.println("nickname=" + nickname);
        System.out.println("avatarUrl=" + avatarUrl);

        TcUser user = UserService.login(code, nickname, avatarUrl);
        System.out.println("user=" + user);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "登录成功");
        result.put("data", user);
        return result;
    }

    @Autowired
    WxService wxUserService;
    
    @PostMapping("/list")
    public List<WxUser> list(){
        return wxUserService.list();
    }



    // ==================== 班级成员相关方法 ====================
    
    /**
     * 根据班级ID获取班级成员列表
     * @param classId 班级ID
     * @return 班级成员列表
     */
    @GetMapping("/classMembers/{classId}")
    public Map<String, Object> getClassMembers(@PathVariable Integer classId) {
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            queryWrapper.orderByDesc("create_time");
            List<WxUser> members = wxUserService.list(queryWrapper);
            
            result.put("code", 200);
            result.put("message", "获取班级成员成功");
            result.put("data", members);
            result.put("count", members.size());
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取班级成员失败：" + e.getMessage());
            result.put("data", null);
        }
        return result;
    }

    /**
     * 根据班级ID和身份获取班级成员列表
     * @param classId 班级ID
     * @param identity 身份（老师/学生/家长）
     * @return 指定身份的班级成员列表
     */
    @GetMapping("/classMembers/{classId}/{identity}")
    public Map<String, Object> getClassMembersByIdentity(@PathVariable Integer classId, @PathVariable String identity) {
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            queryWrapper.eq("identity", identity);
            queryWrapper.orderByDesc("create_time");
            List<WxUser> members = wxUserService.list(queryWrapper);
            
            result.put("code", 200);
            result.put("message", "获取" + identity + "列表成功");
            result.put("data", members);
            result.put("count", members.size());
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取" + identity + "列表失败：" + e.getMessage());
            result.put("data", null);
        }
        return result;
    }

    /**
     * 获取班级学生列表
     * @param classId 班级ID
     * @return 班级学生列表
     */
    @GetMapping("/classStudents/{classId}")
    public Map<String, Object> getClassStudents(@PathVariable Integer classId) {
        return getClassMembersByIdentity(classId, "学生");
    }

    /**
     * 获取班级老师列表
     * @param classId 班级ID
     * @return 班级老师列表
     */
    @GetMapping("/classTeachers/{classId}")
    public Map<String, Object> getClassTeachers(@PathVariable Integer classId) {
        return getClassMembersByIdentity(classId, "老师");
    }

    /**
     * 获取班级家长列表
     * @param classId 班级ID
     * @return 班级家长列表
     */
    @GetMapping("/classParents/{classId}")
    public Map<String, Object> getClassParents(@PathVariable Integer classId) {
        return getClassMembersByIdentity(classId, "家长");
    }

    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/user/{userId}")
    public Map<String, Object> getUserById(@PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            WxUser user = wxUserService.getById(userId);
            if (user != null) {
                result.put("code", 200);
                result.put("message", "获取用户信息成功");
                result.put("data", user);
            } else {
                result.put("code", 404);
                result.put("message", "用户不存在");
                result.put("data", null);
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取用户信息失败：" + e.getMessage());
            result.put("data", null);
        }
        return result;
    }

    /**
     * 检查用户是否在指定班级中
     * @param userId 用户ID
     * @param classId 班级ID
     * @return 检查结果
     */
    @GetMapping("/checkMember/{userId}/{classId}")
    public Map<String, Object> checkUserInClass(@PathVariable Integer userId, @PathVariable Integer classId) {
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", userId);
            queryWrapper.eq("class_id", classId);
            WxUser user = wxUserService.getOne(queryWrapper);
            
            result.put("code", 200);
            result.put("message", "检查完成");
            result.put("isMember", user != null);
            result.put("user", user);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "检查失败：" + e.getMessage());
            result.put("isMember", false);
        }
        return result;
    }

    /**
     * 用户加入班级
     * @param userId 用户ID
     * @param classId 班级ID
     * @param identity 身份
     * @return 操作结果
     */
    @PostMapping("/joinClass")
    public Map<String, Object> joinClass(@RequestParam Integer userId, @RequestParam Integer classId, @RequestParam String identity) {
        Map<String, Object> result = new HashMap<>();
        try {
            WxUser user = wxUserService.getById(userId);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }

            // 检查是否已经在班级中
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", userId);
            queryWrapper.eq("class_id", classId);
            WxUser existingMember = wxUserService.getOne(queryWrapper);
            
            if (existingMember != null) {
                result.put("code", 400);
                result.put("message", "用户已在该班级中");
                return result;
            }

            // 更新用户信息
            user.setClassId(classId);
            user.setIdentity(identity);
            user.setUpdateTime(new java.util.Date());
            
            boolean success = wxUserService.updateById(user);
            if (success) {
                result.put("code", 200);
                result.put("message", "加入班级成功");
                result.put("data", user);
            } else {
                result.put("code", 500);
                result.put("message", "加入班级失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "加入班级失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 用户退出班级
     * @param userId 用户ID
     * @param classId 班级ID
     * @return 操作结果
     */
    @PostMapping("/leaveClass")
    public Map<String, Object> leaveClass(@RequestParam Integer userId, @RequestParam Integer classId) {
        Map<String, Object> result = new HashMap<>();
        try {
            WxUser user = wxUserService.getById(userId);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }

            if (!classId.equals(user.getClassId())) {
                result.put("code", 400);
                result.put("message", "用户不在该班级中");
                return result;
            }

            // 清除班级信息
            user.setClassId(null);
            user.setUpdateTime(new java.util.Date());
            
            boolean success = wxUserService.updateById(user);
            if (success) {
                result.put("code", 200);
                result.put("message", "退出班级成功");
                result.put("data", user);
            } else {
                result.put("code", 500);
                result.put("message", "退出班级失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "退出班级失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取班级成员统计信息
     * @param classId 班级ID
     * @return 统计信息
     */
    @GetMapping("/classStatistics/{classId}")
    public Map<String, Object> getClassStatistics(@PathVariable Integer classId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取所有班级成员
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", classId);
            List<WxUser> allMembers = wxUserService.list(queryWrapper);
            
            // 统计各身份人数
            long teacherCount = allMembers.stream().filter(u -> "老师".equals(u.getIdentity())).count();
            long studentCount = allMembers.stream().filter(u -> "学生".equals(u.getIdentity())).count();
            long parentCount = allMembers.stream().filter(u -> "家长".equals(u.getIdentity())).count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCount", allMembers.size());
            statistics.put("teacherCount", teacherCount);
            statistics.put("studentCount", studentCount);
            statistics.put("parentCount", parentCount);
            
            result.put("code", 200);
            result.put("message", "获取班级统计信息成功");
            result.put("data", statistics);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取班级统计信息失败：" + e.getMessage());
            result.put("data", null);
        }
        return result;
    }


}
